# To change this template, choose Tools | Templates
# and open the template in the editor.

__author__="Evgeny"
__date__ ="$25.09.2010 22:36:26$"

import time
import BaseHTTPServer
import SimpleHTTPServer
import json
from urlparse import urlparse
from urlparse import parse_qs

# from router import GetPoly
from VirtualGraph import GetPoly

HOST_NAME = 'localhost' # !!!REMEMBER TO CHANGE THIS!!!
PORT_NUMBER = 80 #

LAT_Q1 = 'lat1'
LNG_Q1 = 'lng1'
LAT_Q2 = 'lat2'
LNG_Q2 = 'lng2'
PATH_TYPE = 'path-type'

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_HEAD(self):
        self.send_response(200)
        self.end_headers()
    def do_GET(self):
        """Respond to a GET request."""
        if self.headers.getheader('X-Requested-With') == \
        'XMLHttpRequest':            
            self.send_response(200)
            # self.send_header("Content-type", "application/json")
            self.send_header("Content-type", "text/plain")
            self.end_headers()
            u_parsed = urlparse(self.path)
            print 'query ',u_parsed.query
            # @type qdict dict
            qdict = parse_qs(u_parsed.query)
            print 'qdict: '
            print qdict
            start_time = time.clock()
            # @type poly_list list
            poly_list = GetPoly( [ \
            float(qdict[LAT_Q1][0]),\
            float(qdict[LNG_Q1][0]), \
            float(qdict[LAT_Q2][0]),\
            float(qdict[LNG_Q2][0])],\
            str(qdict[PATH_TYPE][0]))
            print "processing time in secs: ", time.clock() - start_time
            #print "Shortest path len: ",len(poly_list)
            result = json.dumps((poly_list))
            self.wfile.write(result)
            #print result
        else:
            SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

    def do_POST(self):
        """Respond to a POST request."""
        print 'having POST request at',self.path, time.asctime()
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.end_headers()
        length = int(self.headers.getheader('content-length'))
        data_string = self.rfile.read(length)
        # try:
        list = json.loads(data_string)
        print list
        result = json.dumps(GetPoly(list[0],list[1]))
            # except:
            # result = 'error'
        self.wfile.write(result)
        # O-o-o-o E!

def run_srv():
    server_class = BaseHTTPServer.HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
    print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)

if __name__ == '__main__':
    run_srv()




